<template>
  <div>
    <el-upload
      ref="elUpload"
      drag
      action
      :auto-upload="false"
      :show-file-list="true"
      multiple
      :http-request="uploadFile"
      :on-success="success"
      :on-change="change"
      :on-error="error"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>

    <el-button @click="handleUpload">Upload</el-button>
  </div>
</template>

<script>
import client from '@/plugins/ossClient'
import { upload, getFileByObjName } from '@/api/file'

export default {
  data() {
    return {
      files: [],
      fileSize: 0,
      uploadSize: 0
    }
  },
  computed: {},
  methods: {
    uploadFile(obj) {
      const file = obj.file
      const objectName = (new Date().getTime() + Math.floor(Math.random() * 10000) + '').split('').reverse().join('') + '.' + file.name.split('.').pop()
      client
        .put(objectName, obj.file)
        .then(res => {
          console.log(res)
          obj.onProgress({ percent: 50 })
          const saveFile = {
            name: file.name,
            size: file.size,
            type: file.name.split('.').pop(),
            serverType: 'oss',
            objectName: objectName
          }
          // 上传文件
          upload(saveFile)
            .then(() => {
              obj.onProgress({ percent: 100 })
              obj.onSuccess()
            })
            .catch(error => {
              console.log(error)
              // 如果报错查看文件是否保入数据库
              getFileByObjName(objectName).then(res => {
                if (!res.data.file) {
                  // 文件不存在删除oss文件
                  this.deleteOssFile(objectName)
                }
              })
            })
        })
        .catch(error => {
          obj.onError(error)
        })
    },
    change(file, fileList) {
      this.files = fileList
      this.fileSize = fileList.length
    },
    success(response, file, fileList) {
      this.uploadSize++
      if (this.uploadSize === this.fileSize) {
        this.$message.success({
          message: '文件上传成功',
          onClose: () => {
            // todo close page
            this.$refs.elUpload.clearFiles()
          }
        })
      }
    },
    error(err, file, fileList) {
      this.$message.error('文件上传失败')
      console.log(err)
    },
    handleUpload() {
      this.$refs.elUpload.submit()
    },
    deleteOssFile(objectName) {
      try {
        client.delete(objectName)
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style>
</style>
